package com.mvc.controller;

import com.db.dao.ProjectDao;
import com.db.entity.Project;
import com.db.entity.WorkingHoursRecord;
import com.db.utility.Tools;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/project")
public class ProjectController {
	
	private static Logger log = Logger.getLogger(ProjectController.class);

    @Autowired
    private ProjectDao projctDao;

	@RequestMapping({"/init","/"})
	public String writeWorkingHour(Model model){

        List<Project> projects = projctDao.findAll();
		
		model.addAttribute("projects", projects);
        model.addAttribute("newProject", new Project());

        Map<Integer, String> projectTypes = new HashMap<Integer, String>();
        for(int i=1; i < Project.EnumProjectType.TOTAL.ordinal(); ++i )
        {
            projectTypes.put(i, Project.getProjectType( Project.EnumProjectType.values()[i] ));
        }
        model.addAttribute("projectTypes", projectTypes);
		return "project/project";
	}

    @RequestMapping({"addProject","/"})
    public void addProject(Project project, HttpServletResponse response) throws IOException {
        log.debug("addProject ajax called");

        String reponseWords;

        project.setType(Project.getProjectType(project.getTypeStr()));
        if(project.getType() == Project.EnumProjectType.NULL)
            reponseWords = "项目类型错误！";


        project.setUuid(Tools.getUUID());
        boolean ok = projctDao.save(project);
        if(!ok) {
            reponseWords = "新增记录失败！";
        } else {
            reponseWords = "新增记录成功！";
        }

        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(reponseWords);
        response.flushBuffer();
    }
	
	
}
